package com.srwl.mytx.widget;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.Present;
import com.srwl.mytx.domain.Reward;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.utils.GlideLoadUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by wei on 2016/6/7.
 */
@RemoteViews.RemoteView
public class LivePresentView extends RelativeLayout {
    private static final String TAG = "LivePresentView";
    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.tv_nick)
    TextView tv_nick;
    @BindView(R.id.gift_image)
    ImageView giftImage;

    @BindView(R.id.gift_num)
    TextView giftCount;
    private long expireTime;
    private int giftNum = 0;
    private int combo = 0; //连击数
    private List<Present> presents;
    private Context context;
    private Reward reward;
    //float comboSize = 1;
    public long COMBOTIME = 400;
    volatile boolean isGiftShowing = false;
    boolean isReadyHide;
    private Handler handler = new Handler();
    private PresentListListener listener;
    private Runnable runnable = new Runnable() {
        /**
         * 礼物连击动画的显示
         */
        @Override
        public void run() {
            giftNum++;
            giftCount.setVisibility(INVISIBLE);
            giftCount.setText("x" + " " + giftNum + "");
            combo--;


            ViewAnimator.animate(giftCount).scale(0, 1).
                    duration(400).onStart(new AnimationListener.Start() {
                @Override
                public void onStart() {
                    giftCount.setVisibility(VISIBLE);
                }
            }).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {

                    if (combo == 0) {
                        if (isReadyHide == false) {
                            Log.d(TAG, "run: 连击消失：" + combo + getId());
                            isReadyHide = true;
                            disappear();
                        }

                    }
                }
            }).start();


            if (combo > 0) {
                Log.d(TAG, "run: runnable被调用了combo：" + combo);
                handler.postDelayed(runnable, COMBOTIME);
            }

        }
    };

    public int getGiftNum() {
        return giftNum;
    }

    public void setGiftNum(int giftNum) {
        this.giftNum = giftNum;
    }

    public int getCombo() {
        return combo;
    }

    public void increatCombo() {
        combo++;
        if (combo == 1) {
            handler.postDelayed(runnable, 300);
        }
    }

    public LivePresentView(Context context) {

        super(context);
        this.context=context;
        init(context, null);
    }

    public LivePresentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init(context, attrs);

    }

    public LivePresentView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs);
        this.context=context;

    }

    private void init(Context context, AttributeSet attrs) {
        LayoutInflater.from(context).inflate(R.layout.widget_left_gift, this);
        ButterKnife.bind(this);
    }

    public void setListener(PresentListListener listener) {
        this.listener = listener;
    }

    public List<Present> getPresents() {
        return presents;
    }

    public void setPresents(List<Present> presents) {
        this.presents = presents;
    }

    public void setName(String name) {
        this.tv_nick.setText(name);
    }

    public void setReward(Reward reward) {
        this.reward = reward;
        giftCount.setText("x" + " " + giftNum + "");
        User user = reward.getUser();
        if (user != null) {
            tv_nick.setText(user.getUsername());
            //Glide.with(this).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(avatar);
            GlideLoadUtils.glideLoad(context, user.getAvatar(), avatar, R.drawable.tx_default_avatar_1);
        }
        /**
         * 加载从服务端获取的图片
         *
         */
       /*

        for (int i = 0; i < presents.size(); i++) {
            String rAmount = reward.getAmount().toString();
            String pAmount = presents.get(i).getAmount().toString();


            if (rAmount.equals(pAmount) ){
                //presents.get(i).getPicture();


                GlideApp.with(this).load(presents.get(i).getPicture()).diskCacheStrategy(DiskCacheStrategy.RESOURCE).into(giftImage);

            }
        }*/

        if (reward.getAmount() == 0.1) {
            giftImage.setImageResource(R.drawable.p_1jiao);
        } else if (reward.getAmount() == 0.01) {
            giftImage.setImageResource(R.drawable.p_1fen);
        } else if (reward.getAmount() == 0.02) {
            giftImage.setImageResource(R.drawable.p_2fen);
        } else if (reward.getAmount() == 0.05) {
            giftImage.setImageResource(R.drawable.p_5fen);
        } else if (reward.getAmount() == 0.2) {
            giftImage.setImageResource(R.drawable.p_2jiao);
        } else if (reward.getAmount() == 0.5) {
            giftImage.setImageResource(R.drawable.p_5jiao);
        } else if (reward.getAmount() == 1) {
            giftImage.setImageResource(R.drawable.p_1yuan);
        } else if (reward.getAmount() == 2) {
            giftImage.setImageResource(R.drawable.p_2yuan);
        } else if (reward.getAmount() == 5) {
            giftImage.setImageResource(R.drawable.p_5yuan);
        } else if (reward.getAmount() == 10) {
            giftImage.setImageResource(R.drawable.p_10yuan);
        } else if (reward.getAmount() == 50) {
            giftImage.setImageResource(R.drawable.p_50yuan);
        } else if (reward.getAmount() == 100) {
            giftImage.setImageResource(R.drawable.p_100yuan);
        }


    }

    public void setAvatar(String avatarUrl) {
        //Glide.with(getContext()).load(avatarUrl).into(this.avatar);
        GlideLoadUtils.glideLoad(context, avatarUrl, avatar);
    }

    public ImageView getGiftImageView() {
        return giftImage;
    }
    //礼物数增加

    public void increatGiftNum() {
        giftNum++;
        //giftCount.setText(giftNum + "");

        giftCount.setVisibility(INVISIBLE);
        giftCount.setText("x" + " " + giftNum + "");
        ViewAnimator.animate(giftCount).scale(0, 1).duration(200).onStart(new AnimationListener.Start() {
            @Override
            public void onStart() {
                giftCount.setVisibility(VISIBLE);
            }
        }).start();

    }

    public void listCombo() {


    }

    public void cleanGiftNum() {
        giftNum = 1;
        giftCount.setText("x" + " " + giftNum + "");
    }

    //重置礼物数量
    public void removerGiftNum() {
        giftNum = 0;

    }

    public void increatExpireTime(long increatTime) {
        this.expireTime += increatTime;
    }

    public long getExpireTime() {
        return expireTime;
    }


    /**
     * 重置过期时间
     *
     * @param replaceExpireTime
     */
    public void replaceExpireTime(long replaceExpireTime) {

        this.expireTime = replaceExpireTime;
    }

    private void disappear() {
        Log.d(TAG, "onStop: 礼物开始消失动画，，，" + getId());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ViewAnimator.animate(LivePresentView.this)
                        .alpha(1, 0)
                        .translationY(-1.5f * LivePresentView.this.getHeight())
                        .duration(800)
                        .onStop(new AnimationListener.Stop() {
                            @Override
                            public void onStop() {
                                Log.d(TAG, "onStop: 礼物消失掉了，，，" + getId());
                                isReadyHide = false;
                                isGiftShowing = false;
                                removerGiftNum();
                                reward = null;
                                if (listener != null) {
                                    listener.onDisappear();
                                }

                            }
                        }).start();


            }
        }, 1500);

    }

    /**
     * 判断礼物是否利用（消费）
     *
     * @param currentReward
     * @return
     */
    public boolean isUseGift(Reward currentReward) {
        if (reward != null && !isReadyHide &&
                reward.getuId().equals(currentReward.getuId())
                && Double.doubleToLongBits(reward.getAmount()) == Double.doubleToLongBits(currentReward.getAmount())) {
            increatExpireTime(COMBOTIME);
            increatCombo();
            return true;

        } else if (!isGiftShowing) {
            showGiftDerect(currentReward);
            increatCombo();
            return true;
        } else {
            return false;

        }
    }

    /**
     * 仅显示礼物
     *
     * @param currentReward
     */
    private void showGiftDerect(final Reward currentReward) {
        Log.d(TAG, "showGiftDerect: 开始显示礼物" + getId());
        isGiftShowing = true;
        setVisibility(View.VISIBLE);
        setReward(currentReward);
        setTranslationY(0);
        ViewAnimator.animate(LivePresentView.this)
                .alpha(0, 1)
                .translationX(-getWidth(), 0)
                .duration(600)
                .onStop(new AnimationListener.Stop() {
                    @Override
                    public void onStop() {
//                        if (combo == 0) {
//                            disappear();
//                        }
                    }
                })
                .start();

        ViewAnimator.animate(giftImage)
                .translationX(-giftImage.getX(), 0)
                .duration(1100)
                .start();
    }


    public interface PresentListListener {
        void onDisappear();
    }


}


